using System;
using System.Text.RegularExpressions;
using miPics.Common;


namespace miPics.BasePage
{

	public abstract class BasePage : System.Web.UI.Page
	{
		private bool _IsLoggedIn = false;

		// constructor
		public BasePage()
		{
			// hook BasePage_Load() onto base Load() event
			this.Load += this.BasePage_Load;
		}

		private void BasePage_Load(object sender, EventArgs e)
		{
			// init login
			this.InitLogin();
		}

		#region User Login
		private void InitLogin()
		{
			// check if user is logged in
			if (
				(Session["userlogin"] != null) && (Session["userlogin"].ToString() == "yes") ||
				(Config.General.AlwaysLoggedIn)
			)
			{
				this.SetIsLoggedIn = true;
			}

			// check if user is requesting a page in the "/Administration" folder, and if they are not logged in, kick them back to home
			// the script name "Default.aspx" is excempt from this rule, since it is used for user login
			Regex Regexp = new Regex(@"/Administration/(\w+)\.aspx$",RegexOptions.IgnoreCase);
			Match Found = Regexp.Match(Request.FilePath);

			if (Found.Success)
			{
				if ((Found.Groups[1].Value.ToLower() != "default") && (!this.IsLoggedIn))
				{
					// user should not be here, kick back to user login screen
					Response.Redirect("~/Administration");
				}
			}
		}

		protected void LoginUser()
		{
			Session["userlogin"] = "yes";

			// redirect back to home
			Response.Redirect("~/");
		}

		protected void LogoutUser()
		{
			Session["userlogin"] = null;
			this.SetIsLoggedIn = false;
		}

		protected bool IsLoggedIn
		{
			get { return this._IsLoggedIn; }
		}

		private bool SetIsLoggedIn
		{
			set 
			{
				this._IsLoggedIn = value;
				((miPics.BasePage.BaseMasterPage)Master).IsLoggedIn = value;
			}
		}
		#endregion
	}

}